templatePath = 'template-path/'
handleCmis401Error= (errorResponse)->
#  console.log('====errorResponse====')
#  console.log(errorResponse)
#  console.log(typeof errorResponse)
  # 断网的时候 0 == xhr.status superagent 当作了 跨域错误或者是用户自己主动abort请求操作
  if(errorResponse.constructor.name == 'Error')
    # 可能是 跨域 也可能是 未联网
    $(document).trigger( "disconnectErr");
    console.log(errorResponse)
    return
  if errorResponse.status == 401
    if window.location.href.indexOf('localhost') != -1
      alert('TOKEN ERROR UPDATE YOUR TOKEN')
    else
      if window.location.href.indexOf('file') != -1 && CmisService.device == 'platform-pad'
        $location.path('/app/logout', false)
      else if window.UCX_relogin && typeof window.UCX_relogin == 'function'
        window.UCX_relogin();
      else
        window.location.href = '/site/re-login?url='+window.location.href
    true
  else
    false
angular.module('UCX.Cmis')
.provider "CmisService", ()->
  service = {
    $get: ()->
      {
        setConfig: (
          url,
          token,
          path = '/',
          baseUrl = '/',
          isDrmRoom = 'false'
          messageToMember = ''
          showMembers = 'true'
          roomLink = ''
          previewDid = ''
          allowExtension = ''
          repository = 'fxcld'
          membershipType = ''
          allowDownload = 'true'
          filePickerModal = ''
          device = ''
          pluginVersion = ''
          fromFillAndSign=false
          cwebToolsApi = ''
          pluginUi = ''
          fileType = ''
          fileSelectMode = ''
          phantomSubscriptionStatus = null
          isEnterpriseSite = false
          cpdfBaseUrl = ''
          cpdfDocBaseUrl = ''
          docOwner = true
          project = ''
          hideRetireNotify
        )->
          ##           cmis连接
          #  atom(php) | browser(咱们这个项目) 下面只介绍browser链接方法 atom同样的 cmis/atom
          #  cmis/browser 只返回default仓库和fxcld仓库
          #  cmis/browser?allRepository=1 返回所有的仓库
          #  cmis/browser?repositoryId=fxcld 只返回fxcld仓库
          ##
          session = cmis.createSession(url+"?repositoryId="+repository)
          session.setToken(token)
          session.setGlobalHandlers(null,handleCmis401Error)
          this.session = session
          this.path = path
          this.cpdfBaseUrl = cpdfBaseUrl
          this.cpdfDocBaseUrl = cpdfDocBaseUrl
          this.token = token
          this.email = decodeURIComponent(token).split(',')[1]
          this.baseUrl = url.replace('cmis/browser','')
          this.isDrmRoom = if isDrmRoom != 'false' && isDrmRoom != '0' then true else false
          this.messageToMember = messageToMember
          this.showMembers = if showMembers != 'false' && showMembers != '0' then true else false
          this.roomLink = roomLink
          this.previewDid = previewDid
          this.allowExtension = if allowExtension == '' then [] else allowExtension.split(',')
          this.repository = repository
          this.device=device
          this.filePickerModal = filePickerModal
          this.device = device
          this.pluginVersion = pluginVersion
          this.fromFillAndSign = fromFillAndSign
          this.membershipType = membershipType
          this.cwebToolsApi = cwebToolsApi
          this.allowDownload = if allowDownload != 'false' && allowDownload != '0' then true else false
          this.pluginUi = pluginUi
          this.fileType = fileType
          this.phantomSubscriptionStatus = phantomSubscriptionStatus
          this.fileSelectMode = fileSelectMode
          this.isEnterpriseSite = isEnterpriseSite
          this.docOwner = if docOwner=='false' then false else true
          this.project=project
          this.isSharedWithMe=this.path.indexOf('Files_Shared_with_Me')>-1
          this.hideRetireNotify = if hideRetireNotify=='true' then true else false
          console.log this
      }
  }
  service
.service "Loading", (toastr, $timeout)->
  toastrInstance = null
  timerPromise = null
  this.open = (content = "uploading")->
    toastrInstance = toastr.info(content, '', {timeOut:0});

    timerPromise = $timeout ()->
      toastr.clear(toastrInstance);
    ,
      20000
  this.close = ()->
    $timeout.cancel(timerPromise)
    toastr.clear(toastrInstance);

  this

.factory "Utils", ($uibModal, toastr, localStorageService, CmisService, toastrConfig, $translate, $timeout, $location)->
  timer = {}
  {
  rootFolder:null,
  templateData:{}
  modalInstance:null
  parentHasRenamed:false
  loadingModal:null
  currentFolder:{},
  searchType:''
  disabledEmail:''
  loadingSearchResult:false
  supportLang:['US','DK','DE','FI','419','LAS','FR','IT','JP','KR','NO','NL','PL','BR','PT','RU','SE','CN','HK','TW']
  currentUrl:''
  isUploadNewVersioning :false
  searchModeIsOn:false
  initTempDataFromTemplate: (templateDate)->


  getEmailDomainFrom:(email)->
    return email.split('@')[1]
  getAttrOfObjBy:(key,obj)->

  isForbiddenFolderName:(folderName)->
    name=[]
    for lang in @supportLang
      if window.CmisLanguage && window.CmisLanguage[lang]
        name.push(window.CmisLanguage[lang]['ConnectedPDF']||'')
        name.push(window.CmisLanguage[lang]['Private']||'')
        name.push(window.CmisLanguage[lang]['cDRM']||'')
    console.log(name)
    if name.indexOf(folderName)>-1
      return true
    else
      return false


  getEmailFromPath:(path)->
    # /User_Homes/ad/mi/admin%40gmail.com/Reading  => admin%40gmail.com
    path0 = path.split('/Reading')[0]
    arr = path0.split('/')
    email=arr.pop()
    return email

  formatAcl:(acl)->
#   accept {"inherited":[{"principalId":"everyone","permissions":["smx:none"]},{"principalId":"ww002@mailinator.com","permissions":["cmis:all"]}]}
#   return [{"principal":{"principalId":"ww002@mailinator.com"},"permissions":["cmis:all"],"isDirect":true}]
    resultAcls = []
    if acl.inherited
      for inheritedAcl in acl.inherited
        result = {
          principal:{'principalId':inheritedAcl.principalId}
          permissions:inheritedAcl.permissions
          isDirect:false
        }
        resultAcls.push(result)

    if acl.direct
      for directAcl in acl.direct
        result = {
          principal:{'principalId':directAcl.principalId}
          permissions:directAcl.permissions
          isDirect:true
        }
        resultAcls.push(result)
    resultAcls

  connectCmis : ()->
    baseUrl = 'https://cloud-demo.connectedpdf.com/'
    url = 'https://cloud-demo.connectedpdf.com/cmis/browser'

    calculatePath = (userEmail) ->
      lowerEmail = userEmail.toLowerCase()
      cleanId = (lowerEmail + 'aaaa').replace(/[^a-zA-Z]/g, '')
      result = cleanId.substring(0, 2) + '/' + cleanId.substring(2, 4) + '/' + lowerEmail
      path = '/User_Homes/' + result + '/Reading'
      path
    if window.FX
      if !window.localStorage
        token = this.getCookie('share_plugin_token')
        baseUrl = this.getCookie('share_plugin_baseUrl')
        url = this.getCookie('share_plugin_url')
      else
        token = localStorage.getItem('share_plugin_token') || this.getCookie('currentToken')
        baseUrl = localStorage.getItem('share_plugin_baseUrl')
        url = localStorage.getItem('share_plugin_url')
      if window.phantomOnlineGlobalConfig
        baseUrl = phantomOnlineGlobalConfig.apiUrl
        url = baseUrl + 'cmis/browser'
      token = decodeURIComponent(token)
      email = token.split(',')[1]
      path = calculatePath(email)
    else
      console.log('====Utils====')
      console.log(this)
      token = this.getCookie('currentToken') || CmisService.token
      email = this.getCookie('currentEmail') || CmisService.email
      path = calculatePath(email)
    CmisService.setConfig url, token, path, baseUrl, false, '', false, '', '', '', 'fxcld', '', '', '', 'phantom-online', '', false


  setContentStream:(params,successCallback,errorCallback) ->
    docId = params.id;
    connectCmis();
    CmisService.session.getContentStream(docId, true).ok (data)->
      console.log('filedata.....',data);

      CmisService.session.setContentStream(docId, data).ok (data2)->
        console.log('setContentStreamfiledata222222222.....',data2);
        successCallback && successCallback()
      .notOk (error)->
        if Utils.handleCmis401Error(error)
          return
        errorCallback && errorCallback(error)
    .notOk (error)->
      if Utils.handleCmis401Error(error)
        return
      errorCallback && errorCallback(error)

  urlParaToObj: (urlPara, needEncode) ->
    obj = {}
    if urlPara.indexOf('%')>-1
      urlPara = decodeURIComponent(urlPara)
    if urlPara.indexOf('&') != -1
      arr = urlPara.split('&')
      k = 0
      len1 = arr.length
      while k < len1
        i = arr[k]
        if needEncode
          obj[i.split('=')[0]] = encodeURIComponent(i.split('=')[1])
        else
          obj[i.split('=')[0]] = i.split('=')[1]
        k++
    else
      if needEncode
        obj[urlPara.split('=')[0]] = encodeURIComponent(i.split('=')[1])
      else
        obj[urlPara.split('=')[0]] = urlPara.split('=')[1]
    obj
  urlObjToUrlPara: (urlParaObj) ->
    #  {a:1,b:3} =>  a=1&b=3
    result=''
    for key,value of urlParaObj
      result+=key+'='+value+'&'
    strLength=result.length
    if strLength==0
      result=''
    else
      result=result.slice(0,strLength-1)
    result
  getArgsFromUrl:(url)->
    if (!url)
      url = location.href
    index = url.indexOf('?')
    if (index == -1)

    else
      urlParas = url.slice(index + 1)
      result = urlParaToObj(urlParas)
      console.log(result)
    return result
  sendGaEvent: (category, action, label) ->
    if window.testGroupId
      testGroupId='_'+window.testGroupId
    else
      testGroupId=''
    if window.sendGa
      window.sendGa('send',{
        hitType: 'event'
        eventCategory: category
        eventAction: action+testGroupId
        eventLabel: label
        eventValue: 0
      })
      return false
    if window.ga and typeof window.ga == 'function'
      if CmisService.device=='foxitReader'
        ga('file_picker.send', {
          hitType: 'event',
          eventCategory: 'Foxit Drive Plugin',
          eventAction: 'plugin_web '+action+' '+category+testGroupId,
          eventLabel: label,
          eventValue: 0
        })
#        ga('send',{
#          hitType: 'event'
#          eventCategory: category
#          eventAction: action+category+testGroupId
#          eventLabel: label
#          eventValue: 0
#        })
      else
        ga('send',{
          hitType: 'event'
          eventCategory: category
          eventAction: action+testGroupId
          eventLabel: label
          eventValue: 0
        })
    else
      if window.FX && window.FX.app && window.FX.app.sendMessage
        window.FX.app.sendMessage({
          type:'gaEvent',
          data:{
            eventName:category
            eventLabel:action+label
          }
        })
  containIllegalChar:(str)->
    illegalCharacters=['/', '\\', ':', '"', '*', '?', '<', '>', '|', '%', '&']
    for char in illegalCharacters
      if str.indexOf(char)>-1
        return true
    return false
  getOsName:()->
    sUserAgent = navigator.userAgent
    isWin = (navigator.platform == "Win32") || (navigator.platform == "Windows")
    isMac = (navigator.platform == "Mac68K") || (navigator.platform == "MacPPC") || (navigator.platform == "Macintosh") || (navigator.platform == "MacIntel")
    isUnix = (navigator.platform == "X11") && !isWin && !isMac
    isLinux = (String(navigator.platform).indexOf("Linux") > -1)
    if(isWin)
      OS = 'windows'
    if isMac
      OS = 'mac'
    if isUnix
      OS = 'unix'
    if isLinux
      OS = 'linux'
    return OS
  isIE10:()->
    return navigator.appVersion.indexOf("MSIE 10") != -1
  isIEorEdge:()->
    IERESULT = false
    userAgent = navigator.userAgent
    isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1
    if (navigator.appVersion.indexOf("MSIE 10") != -1)
      IE10=true
    else
      IE10=false

    if (userAgent.indexOf("Trident") != -1 && userAgent.indexOf("rv:11") != -1)
      IE11=true
    else
      IE11=false

    if (userAgent.indexOf('Edge')>-1)
      IEEdge=true
    else
      IEEdge=false
    if isIE || IE11 || IE10 || IEEdge
      IERESULT = true

    return IERESULT
  isFireFox:()->
    return navigator.userAgent.toLowerCase().indexOf('firefox')>-1
  isSafari:()->
    return navigator.userAgent.indexOf("Safari") > -1 && navigator.userAgent.indexOf("Chrome") == -1
  browserIsIE:()->
    if (navigator.appVersion.indexOf("MSIE 10") != -1)
#        window.alert('This is IE 10')
      IE10=true
    else
      IE10=false
    #     detect ie11
    UAString = navigator.userAgent
    if (UAString.indexOf("Trident") != -1 && UAString.indexOf("rv:11") != -1)
#        window.alert('This is IE 11');
      IE11=true
    else
      IE11=false
    if IE11 || IE10
      IE = true
    else
      IE = false
    return IE

  showFilenameTooltip:(document)->
#    console.log document.id
    id=document.id
#    Todo 用现成的  browserIsIE方法
    if (navigator.appVersion.indexOf("MSIE 10") != -1)
#        window.alert('This is IE 10')
      IE10=true
    else
      IE10=false
    #     detect ie11
    UAString = navigator.userAgent

    if (UAString.indexOf('Edge')>-1)
      IEEdge=true
    else
      IEEdge=false
    if (UAString.indexOf("Trident") != -1 && UAString.indexOf("rv:11") != -1)
#        window.alert('This is IE 11');
      IE11=true
    else
      IE11=false
    if IE11 || IE10 || IEEdge
      IE = true
    else
      IE = false
    init=()->
      onloadToolHint=$('[data-id="'+id+'"]').find('.tooltip-hint').width()
      if onloadToolHint && parseInt(onloadToolHint)>0
        if IE
          $('div[data-id="'+id+'"]').find('.tooltip-hint-parent').find('.long-words-handle').css('width','auto')
          $('tr[data-id="'+id+'"]').find('.tooltip-hint-parent').find('.long-words-handle').css('width','auto')
        if $('div[data-id="'+id+'"]').length && $('div[data-id="'+id+'"]').find('.tooltip-hint-parent').width()<$('div[data-id="'+id+'"]').find('.tooltip-hint').width() || $('tr[data-id="'+id+'"]').length && $('tr[data-id="'+id+'"]').find('.tooltip-hint-parent').width()-12<=$('tr[data-id="'+id+'"]').find('.tooltip-hint').width()
          if $('[data-id="'+id+'"]').find('.tooltip-hint-parent').hasClass('not-show-tooltip')
            $('[data-id="'+id+'"]').find('.tooltip-hint-parent').removeClass('not-show-tooltip')
        else
#          console.log 'add'
#          console.log $('[data-id="'+id+'"]').find('.tooltip-hint-parent')
#          console.log $('[data-id="'+id+'"]').find('.tooltip-hint-parent').width()
#          console.log $('[data-id="'+id+'"]').find('.tooltip-hint').width()
          $('[data-id="'+id+'"]').find('.tooltip-hint-parent').addClass('not-show-tooltip')
        if IE
          $('div[data-id="'+id+'"]').find('.tooltip-hint-parent').find('.long-words-handle').css('width','100%')
          $('tr[data-id="'+id+'"]').find('.tooltip-hint-parent').find('.long-words-handle').css('width','100%')
      else
        $timeout ()->
          init()
        , 1000
    init()
  sqlContainIllegalChar:(str)->
    illegalCharacters=['/', '\\', ':', '"', '*', '?', '<', '>', '|', '%', "'", '&']
    for char in illegalCharacters
      if str.indexOf(char)>-1
        return true
    return false
  translateErrorMsg : (responseJsonDate, args)->
    if responseJsonDate.errorCode
      $translate(responseJsonDate.errorCode, args).then(
        (text)->
          toastr.warning(text)
      ,
        ()->
          toastr.warning(responseJsonDate.message)
      )
    else
      toastr.warning(responseJsonDate.message)
  getFileExt: (fileName)->
    index = fileName.lastIndexOf('.')
    if index != -1
      ext = fileName.substr(index+1).toLowerCase()
    else
      ext = ''
    ext
  isImg: (document)->
    mimeType = if document.type then document.type else if document.contentStreamMimeType then document.contentStreamMimeType else ''
    mimeType.split('/')[0] == 'image'
  isText: (document)->
    mimeType = if document.type then document.type else if document.contentStreamMimeType then document.contentStreamMimeType else ''
    mimeType.split('/')[0] == 'text'
  isAllowExtension: (document)->
    ext = this.getFileExt(document.name)
    CmisService.allowExtension.length ==0 || CmisService.allowExtension.indexOf(ext) > -1
  isPdf: (document)->
    mimeType = if document.type then document.type else if document.contentStreamMimeType then document.contentStreamMimeType else ''
    mimeType == 'application/pdf' || mimeType == 'pdf'
  getMimeTypeFromExt: (fileName)->
    ext = this.getFileExt(fileName)
    mimeTypeMap={
      'pdf':'application/pdf'
      'doc':'application/msword'
      'ppt':'application/vnd.ms-powerpoint'
      'xls':'application/vnd.ms-excel'
      'wri':'application/x-mswrite'
      'rtf':'application/rtf'
      'docx':'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
      'pptx':'application/vnd.openxmlformats-officedocument.presentationml.presentation'
      'xlsx':'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      'txt':'text/plain'
      'bmp':'image/bmp'
      'png':'image/png'
      'gif':'image/gif'
      'jpeg':'image/jpeg'
      'jeg':'image/jpeg'
      'tiff':'image/tiff'
      'zip':'application/zip'
      'rar':'application/x-rar'
    }
    mimeType = mimeTypeMap[ext]||''
    return mimeType
  canPreview: (document)->
    #  https://jira.foxitsoftware.cn/browse/CBASE-362 support type is here
    #  https://jira.foxitsoftware.cn/browse/CVAS-560  具体预览的 情况
    allowPreviewTypes = [
      'application/pdf'
      'application/msword'
      'application/vnd.ms-powerpoint'
      'application/vnd.ms-excel'
      'application/x-mswrite'
      'application/rtf'
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
      'application/vnd.openxmlformats-officedocument.presentationml.presentation'
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      'text/plain'
      'image/bmp'
      'image/png'
      'image/gif'
      'image/jpeg'
      'image/tiff'
    ]
    mimeType = if document.contentStreamMimeType then document.contentStreamMimeType else ''
    allowPreviewTypes.indexOf(mimeType) > -1
  localOpenDocumentPreview: (document)->
    allowPreviewTypes = ['application/vnd.oasis.opendocument.text', 'application/vnd.oasis.opendocument.text-template', 'application/vnd.oasis.opendocument.presentation-template', 'application/vnd.oasis.opendocument.presentation', 'application/vnd.oasis.opendocument.spreadsheet', 'application/vnd.oasis.opendocument.spreadsheet-template']
    mimeType = if document.contentStreamMimeType then document.contentStreamMimeType else ''
    allowPreviewTypes.indexOf(mimeType) > -1
  isOther: (document)->
    !this.isImg(document) && !this.isText(document) && !this.isPdf(document)
  showLoading: (content)->
    @loadingModal = $uibModal.open {
      templateUrl: templatePath + 'loading.html'
      windowClass:'loading-modal'
      controller: 'LoadingController'
      backdrop: 'static'
      resolve: {
        content: ()->
          content
      }
    }
    false
  closeLoading: ()->
    if @loadingModal
      @loadingModal.dismiss()
  confirm: (confirmContent,confirmTitle,confirmBtnText,cancelBtnText, callback,cancelFn)->
    modalInstance = $uibModal.open {
      templateUrl: templatePath + 'confirm.html'
      controller: 'ConfirmController'
      windowClass:'modal-opacity'
      resolve: {
        content: ()->
          confirmContent
        title: ()->
          confirmTitle
        confirmBtnText: ()->
          confirmBtnText
        cancelBtnText: ()->
          cancelBtnText
      },
      backdrop: 'static'
    }
    modalInstance.result.then (reason)->
      callback && callback(reason)
    ,()->
      cancelFn && cancelFn()
    false
  getFullLang: (lang)->
    # US -> en-US
    map = {
      US:'en-US'


      DK:'da-DK'
      DE:'de-DE'
      FI:'fi-FI'
      '419':'es-419'
      LAS:'es-419'
      FR:'fr-FR'

      IT:'it-IT'
      JP:'ja-JP'
      KR:'ko-KR'
      NO:'nb-NO'

      NL:'nl-NL'
      PL:'pl-PL'
      BR:'pt-BR'
      PT:'pt-PT'

      RU:'ru-RU'
      SE:'sv-SE'
      CN:'zh-CN'
      HK:'zh-HK'
      TW:'zh-TW'

    }
    if(map[lang])
      return map[lang]
    else
      return 'en-US'

  isValidEmail: (email)->
    emailPattern=/^[a-zA-Z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/
    isValidEmail=emailPattern.test(email);
    return isValidEmail
  isInGroup: (groupName)->
    # support for the enterprise site share plugin
    if window.sharePlugin && window.sharePlugin.groups
      console.log('====isInGroup')
      console.log(groupName)
      console.log(typeof groupName)
      validGroupNames = window.sharePlugin.groupsNameArray
      validGroupIds = window.sharePlugin.groupsIdArray
    else
      return false
    if groupName in validGroupNames
      return true
    else
      return false
  success: (content)->
    toastr.success content.toString()
  warning: (content)->
    toastr.warning content.toString()

  info: (content)->
    toastr.info content.toString()
  clearToastr: ()->
    toastr.clear()
  getSort: ()->
    if localStorageService.isSupported
      folderOrderBy = localStorageService.get "folder-order-by"
      folderOrderBy = if folderOrderBy then folderOrderBy else '-contentStreamLength'
    else
      folderOrderBy = '-contentStreamLength'
    folderOrderBy
  getFileSort: ()->
    if localStorageService.isSupported
      fileSort = localStorageService.get "file-order-by"
      #      console.log fileSort
      if fileSort == null
        fileSort=true
#      console.log fileSort
    else
      fileSort = true
    fileSort
  getEmailPrefix: (email)->
    # 123@qq.com return 123
    # group need to use groupName instead groupId
    if @.isValidEmail(email)
      return email.split('@')[0]
    else
      if window.sharePlugin && window.sharePlugin.groupsNameArray
        return  if window.sharePlugin.groupsIdToNameMap[email.toLowerCase()] then window.sharePlugin.groupsIdToNameMap[email.toLowerCase()] else email.toLowerCase()
      else
        return email

  getLanguage : ()->
    if localStorageService.isSupported
      language = localStorageService.get "language"

      language = if language then language else 'US'
    else
      language = 'US'
#    console.log('getLang')
#    console.log(language)
    language
  handleTokenError : (error)->
    if error && error.message == 'TOKEN_ERROR'
      if window.location.href.indexOf('localhost') != -1
        alert('TOKEN ERROR UPDATE YOUR TOKEN')
      else
        if window.location.href.indexOf('file') != -1 && CmisService.device == 'platform-pad'
          $location.path('/app/logout', false)
        else if window.UCX_relogin && typeof window.UCX_relogin == 'function'
          window.UCX_relogin();
        else
          window.location.href = '/site/re-login?url='+window.location.href

  handleCmis401Error: (errorResponse)->
    handleCmis401Error(errorResponse)
  rebound : (key, callback, time)->
    # debouce 例如用户间隔内连续输入 仅仅执行最后一次
    if !timer
      timer={}
    if typeof timer[key] != 'undefined'
      $timeout.cancel(timer[key])
    timer[key] = $timeout( ()->
      callback()
    , time)
#  wait for dom load then callback
  waitForDomReady: (elemSelector,successfulCallback,errCallback,interval,totalWaitSec)->
    _this = this
    if !interval
      interval = 200
    if !totalWaitSec
      totalWaitSec = 10000
    count = 0
    timer = null
    if $(elemSelector).length==0
      timer = setTimeout(()->
        count++
        if count>=totalWaitSec/interval
          if errCallback
            errCallback()
          console.log ' $(elemSelector) does not exist '
          return false
        else
          _this.waitForDomReady(elemSelector,successfulCallback,errCallback,interval,totalWaitSec)
      ,interval)
    else
      if successfulCallback
        successfulCallback()
  calculateDaysBetween: (date1,date2)->
   # 2017-02-12    2014-04-30   return 1019
    date1_arr = date1.split('-')
    date1_year = date1_arr[0]
    date1_month = parseInt(date1_arr[1],10)-1
    date1_day = parseInt(date1_arr[2],10)

    date2_arr = date2.split('-')
    date2_year = date2_arr[0]
    date2_month = parseInt(date2_arr[1],10)-1
    date2_day = parseInt(date2_arr[2],10)

    days = parseInt((new Date(date2_year,date2_month,date2_day)-new Date(date1_year,date1_month,date1_day))/1000/60/60/24)
    console.log('日期相差',days)
    return days
  formatDate: (dateType)->
#   dateType can be new Date()  new Date(year,month,date)
#   date type to  2014-03-03 or 2014-1-1
    date = dateType.getDate()
    month = parseInt(dateType.getMonth())+1
    year = dateType.getFullYear()
    return year+'-'+month+'-'+date
  getCookie: (key)->
    reg=new RegExp("(^| )"+key+"=([^;]*)(;|$)");
    if(arr=document.cookie.match(reg))
      return unescape(arr[2]);
    else
      return '';

  # READ ONLY FOLDERS: cannot rename, cannot delete, cannot move to other folders, cannot move other thinks to these folders, cannot upload file cannot create folder into these folders...
  readOnlyFolders: ()->
    return ["/Webforms/", "/Connectedpdf/", "/ConnectedPDF/", "/ConnectedPDF/cDRM/", "/ConnectedPDF/cDRM/Private/"];
  }
.factory "UploadQueue", (CmisService, $uibModal, ModelService, $rootScope, $translate, $timeout, Utils, ApiService, $interval)->
  CmisServiceSession = CmisService.session
  {
    barIsOpen:true
    uploading: false
    queueFiles:[],
    hasErrMsg:false
    isBarOpen:()->
      @barIsOpen
    isUploading:()->
      @uploading
    hasErrMsgFunc:()->
      @hasErrMsg
    checkCDRMConvertingStatus:(file,convertMissionId,successCallback)->
      _this = this
      console.log('===qqqq')
      # 仓库里面的file list实时添加 新file
      # notSetPermission 控制上传完成 设置permission 不填默认 设置权限  true 上传完成不设置权限
      initCmisFile=(file,data,needSetPermission)->
        ApiService.getCmisInfoById(file.cmisId,(cmisData)->
          console.log('====getCmisInfoById')
          if !cmisData.succinctProperties
            cmisData.succinctProperties = cmisData.properties
          cmisData.acl.aces =Utils.formatAcl(cmisData.acl)
          if !cmisData.allowableActions
            cmisData.allowableActions = cmisData.allowable_actions
          newFile = ModelService.createDocument cmisData
          tempFolder = ModelService.getObjectById(file.targetId)
          tempFolder.children = [] if !tempFolder.children
          tempFolder.children.push(newFile)
          file.status = $translate.instant('success')
          Utils.sendGaEvent "Document", "Upload", newFile.id
          newFile.createActivity "upload-document", {document_name: newFile.name, document_id: newFile.id}
          newFile.cDocId=data.data.cDocID
          _this.uploadNext(successCallback)
          if successCallback
            successCallback(newFile,needSetPermission)
        ,(err)->
          console.log(err)
        )
      # 1.upload -> cws server 2.convert to cDRM 3.move to cmis repo
      # 循环
      #      (ApiService.checkCDRMConvertingStatus())
      # file.convertStatus 0=转换中  1=转换成功
      convertFn=()->
        if file.checkConvertAjax
          file.checkConvertAjax.abort()
        file.checkConvertAjax=ApiService.checkCDRMConvertingStatus(convertMissionId, (data)->
          file.convertStatus=1
          # https://jira.foxitsoftware.cn/browse/CPDF-3186
          # convertStatus=-2 taskStatus=3 表示上传的是cDrm文档，并且上传的用户不是该文档的Owner, 需要给出说么 不允许上传
          # convertStatus=-2 taskStatus=1 表示上传的是cDrm文档，需要获取一下该文档的权限，询问是否要重新设置权限
          if data && data.data && data.data.convertStatus==-2 && data.data.taskStatus==3
            # not cDRM owner
            file.isError = true
            _this.hasErrMsg = true
            file.status = $translate.instant('Error')
            file.errorMsg = $translate.instant('not_cDRM_owner')
            Utils.confirm(file.errorMsg,$translate.instant('set_permission'),$translate.instant('close'),null)
            file.isUploaded = true
            file.statusCode = 3
            file.percent = 0
            file.loaded = 0
            _this.uploading = false
            _this.barIsOpen = true
            _this.uploadNext(successCallback)
          else if data && data.data && data.data.convertStatus==-2 && data.data.taskStatus==1
            # owner and cDRM file
            console.log(' it is goes to here ')
            file.cmisId=data.data.cmisID
            file.id=data.data.cmisID
            initCmisFile(file,data,true)
            $timeout(()->
              $uibModal.open {
                templateUrl: templatePath + 'adjust-cDRM-perm.html'
                controller: 'adjustCDRMPermissionCtrl'
                windowClass:'modal-opacity'
                resolve: {
                  file: ()->
                    file
                  data: ()->
                    data.data
                },
                backdrop: 'static'
              }
            )
          else if data && data.data && data.data.taskStatus==2
            file.isError = true
            _this.hasErrMsg = true
            file.status = $translate.instant('Error')
            file.errorMsg = $translate.instant('no_support_convert_this_type')
            Utils.warning($translate.instant('no_support_convert_this_type'))
            file.isUploaded = true
            file.statusCode = 3
            file.percent = 0
            file.loaded = 0
            _this.uploading = false
            _this.barIsOpen = true
            _this.uploadNext(successCallback)
          else
            file.cmisId=data.data.cmisID
            initCmisFile(file,data)
        ,(err)->
          if err && err.code!=500
            file.cDRMConvertTimer = $timeout(()->
              _this.checkCDRMConvertingStatus(file,convertMissionId,successCallback)
            ,3000)
          else
            file.isError = true
            _this.hasErrMsg = true
            file.status = $translate.instant('Error')
            file.errorMsg = $translate.instant('server_error')
            Utils.warning(file.errorMsg)
            file.isUploaded = true
            file.statusCode = 3
            file.percent = 0
            file.loaded = 0
            _this.uploading = false
            _this.barIsOpen = true
            _this.uploadNext(successCallback)
        )
      if !file.convertStatus
        if !file.cDRMConvertTimer
          convertFn()
        else
          $timeout.cancel(file.cDRMConvertTimer)
          convertFn()

    add: (file, targetId, options, versionType, successCallback)->
      queueFile = {
        file: file
        targetId: targetId
        options: options
        versionType: 'major'
        isUploaded: false
        convertMissionID: ''
        convertStatus: 0
        checkConvertAjax: null
        status: $translate.instant('waiting')
        statusCode:1
        cDRMConvertTimer:null
        loaded: 0
        percent: 0
        cmisId: ''
      }
      @queueFiles.unshift(queueFile)
      @showProgressBar()
      @uploadNext(successCallback)
    getNextFile: ()->
      return file for file in @queueFiles when !file.isUploaded

    uploadNext: (successCallback)->
      _this = this
      file = @getNextFile()
      if file
        file.statusCode=2
      if !file
        @uploading = false
        if @hasErrMsg
          @barIsOpen = true
        else
          @barIsOpen = false
#        @barIsOpen = false
#        $('#progress-bar-modal').hide('slow')
#        $('#progress-bar').hide('slow')
#        $rootScope.$apply()
        return
      if @uploading
        @barIsOpen = true
#        $('#progress-bar').show('slow')
        return
      @uploading = true
      @barIsOpen = true
#      $('#progress-bar').show('slow')

      okFunction = (object,convertMissionID)->
        if object
          newFile = ModelService.createDocument object
          tempFolder = ModelService.getObjectById(file.targetId)
          tempFolder.children = [] if !tempFolder.children
          tempFolder.children.push(newFile)
          Utils.sendGaEvent "Document", "Upload", newFile.id
          newFile.createActivity "upload-document", {document_name: newFile.name, document_id: newFile.id}
        file.isUploaded = true
        file.statusCode = 0
        _this.uploading = false
        if convertMissionID
          file.status = $translate.instant('converting')
          file.convertMissionID=convertMissionID
          _this.checkCDRMConvertingStatus(file,file.convertMissionID,successCallback)
        else
          file.status = $translate.instant('success')
          _this.uploadNext(successCallback)
          if successCallback
            successCallback()



      notokFunction = (r)->
        if Utils.handleCmis401Error(r)
          return
        if r && r.text
          try
            data = JSON.parse(r.text)
          catch e

          file.isError = true
          _this.hasErrMsg = true
          file.status = $translate.instant('Error')
          file.statusCode = 3
          file.percent = 0
          file.loaded = 0
          if data
            file.errorMsg = $translate.instant(data.errorCode,{name:file.file.name})
          else
            file.errorMsg = $translate.instant('Error',{name:file.file.name})
          file.isUploaded = true
          _this.uploading = false
          _this.barIsOpen = true
          _this.uploadNext(successCallback)
          if successCallback
            successCallback()


      progressFunction = (e)->
        console.log(e)
        file.loaded = e.loaded
        file.total = e.total
        file.percent = Math.floor(e.loaded/e.total*100)
        file.status = $translate.instant('uploading')
        if successCallback
          successCallback()

      if CmisService.isAndroid
        filePath = encodeURI(file.file.filepath)
        # for android
        console.log 'file://' + filePath
        window.resolveLocalFileSystemURL 'file://' + filePath, ((fileEntry) ->
          console.log fileEntry
          fileEntry.file (localfile) ->
            reader = undefined
            reader = new FileReader

            reader.onloadend = (fileReadResult) ->
              data = undefined
              data = new Uint8Array(fileReadResult.target.result)
              fileBolbData = new Blob([ data ], type: file.file.type)
              _this.currentUploadFile = CmisService.session.createDocument(file.targetId, fileBolbData, file.options, file.file.type, file.versionType)
              _this.currentUploadFile.ok(okFunction).notOk(notokFunction).getRequest().on 'progress', progressFunction

            reader.readAsArrayBuffer localfile
        ), (error) ->
          console.log error
      else
        # convert to cPDF then upload
        tempFolder = ModelService.getObjectById(file.targetId)
        if tempFolder.isCDRMFolder()
          targetFolderPath = tempFolder.path
          _this.currentUploadFile=ApiService.uploadToCWS(targetFolderPath, file.file,file.file.name,(convertMissionId)->
            okFunction(null,convertMissionId)
          ,()->
            console.log('error')
            notokFunction()
          ,(e)->
            console.log('====progress')
            progressFunction(e)
          )
        # normal upload file
        else
          reader = new FileReader
          mimeType = Utils.getMimeTypeFromExt(file.file.name)
          reader.addEventListener("loadend", (fileReadResult)->
            data = new Uint8Array(fileReadResult.target.result)
            fileBlobData = new Blob([ data ], type: mimeType||file.file.type)
            _this.currentUploadFile = CmisService.session.createDocument(file.targetId, fileBlobData, file.options, mimeType||file.file.type, file.versionType)
            _this.currentUploadFile.ok(okFunction).notOk(notokFunction).getRequest().on 'progress', progressFunction

          )
          reader.readAsArrayBuffer(file.file)
    showProgressBar: ()->
      _this = this
      $('#progress-bar-modal').show('slow')
  }
.factory "ApiService", (CmisService, $translate,$q, $timeout,Utils,Loading,$http,ModelService, localStorageService)->
  CmisServiceSession = CmisService.session
  {
#    https://cws-docker.connectedpdf.com/cpdfapi/v1/users/personnel-relationship?access-token=
    getUserInputList:()->
      deferred = $q.defer()
      #      https://online.cpdf360.cn/api/account?type=1&page=1&access-token=5b3ad81be4b098d865668c13%2Cbchtze37615%40027168.com
      url=CmisService.cpdfBaseUrl + 'cpdfapi/v1/users/name-list?keyword=%40&access-token='+CmisService.token
      $.ajax({
        type: 'GET'
        url: url
        success: (data)->
          console.log(data)
          if data && data.ret==0
            deferred.resolve(data.data)
          else
            deferred.reject(data)
        error: (err)->
          deferred.reject(err)
      })
      deferred.promise
    createUserRelationship:(email)->
      deferred = $q.defer()
      postData={
        "email":email
      }
      #      https://online.cpdf360.cn/api/account?type=1&page=1&access-token=5b3ad81be4b098d865668c13%2Cbchtze37615%40027168.com
      url=CmisService.cpdfBaseUrl + 'cpdfapi/v1/users/personnel-relationship?access-token='+CmisService.token
      $.ajax({
        type: 'POST'
        url: url
        data: postData
        success: (data)->
          console.log(data)
          if data && data.ret==0
            deferred.resolve(data.data)
          else
            deferred.reject(data.data)
        error: (err)->
          deferred.reject(err)
      })
      deferred.promise
    getUserList:()->
      deferred = $q.defer()
#      https://online.cpdf360.cn/api/account?type=1&page=1&access-token=5b3ad81be4b098d865668c13%2Cbchtze37615%40027168.com
      url=CmisService.cpdfDocBaseUrl + 'api/account?type=1&page=1&per-page=9999999&access-token='+CmisService.token
      $.ajax({
        type: 'GET'
        url: url
        success: (data)->
          console.log(data)
          if data && data.code==100000
            deferred.resolve(data.data)
          else
            deferred.reject(data.data)
        error: (err)->
          deferred.reject(err)
      })
      deferred.promise
    getCompressFileLink:(cmisIdArr,successfulCallback,errCallback,useUrlDownload)->
      url=CmisService.cpdfBaseUrl+'cpdfapi/v1/server/compressed-files?access-token='+CmisService.token
      postData={
        'cmisIds[]':cmisIdArr
      }
      xhr = new XMLHttpRequest
      xhr.open 'POST', url, true
      xhr.responseType = 'arraybuffer'

      xhr.onload = ->
        if @status == 200
          filename = ''
          disposition = xhr.getResponseHeader('Content-Disposition')
          console.log(disposition)
          if disposition and disposition.indexOf('attachment') != -1
            filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
            matches = filenameRegex.exec(disposition)
            if matches != null and matches[1]
              filename = matches[1].replace(/['"]/g, '')
          type = xhr.getResponseHeader('Content-Type')
          if typeof File == 'function' && !Utils.isIEorEdge()
            blob = new File([@response],filename,type:type)
          else
            blob =new Blob([@response],type:type)
          if typeof window.navigator.msSaveBlob != 'undefined'
      # IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
            window.navigator.msSaveBlob blob, filename
          else
            URL = window.URL or window.webkitURL
            downloadUrl = URL.createObjectURL(blob)
            if filename && !useUrlDownload
      # use HTML5 a[download] attribute to specify filename
              a = document.createElement('a')
              # safari doesn't support this yet
              if typeof a.download == 'undefined'
                window.location = downloadUrl
              else
                a.href = downloadUrl
                a.download = filename
                document.body.appendChild a
                a.click()
            else
              window.location = downloadUrl
            $timeout (->
              URL.revokeObjectURL downloadUrl
              return
            ), 100
        # cleanup
        successfulCallback && successfulCallback()
        return

      xhr.setRequestHeader 'Content-type', 'application/x-www-form-urlencoded'
      xhr.send $.param(postData)
#      $.ajax({
#        type: 'POST'
#        url: url
#        data: postData
#        success: (data,textStatus, request)->
#          fileName=request.getResponseHeader('Content-Disposition')
#          mimeType=request.getResponseHeader('Content-Type')
#          console.log(fileName)
#          console.log(mimeType)
#          console.log(request)
#          if data && !data.ret
#            if successfulCallback
#              successfulCallback(data,fileName,mimeType)
#          else
#            errCallback && errCallback(data)
#        error: (err)->
#          console.log(err)
#          errCallback && errCallback(err)
#      })

    checkUserStatus:(email)->
      deferred = $q.defer()
      url=CmisService.cpdfDocBaseUrl+'api/user/status?email='+email
      $.ajax({
        type: 'GET'
        url: url
        success: (data)->
          console.log(data)
          # data.code 100004 not register
          # data.code 100000 可以使用
          # data.code 900027 register not approval
          if data && data.code==100000
            deferred.resolve({enabled:email})
          else if data && data.code==100004
            deferred.resolve({notRegister:email})
#          else if data && (data.code==900027 || data.code==900028 || data.code==900029)
#            deferred.resolve({notApproval:email})
          else
            # 900027 900028 900029 900022 统一为 不批准
            deferred.resolve({notApproval:email})
        error: ()->
          deferred.resolve({disabled:email})
          
      })
      deferred.promise
    syncCmisFileNameToCdrm:(file,successfulCallback,errCallback)->
      cmisId=file.id
      if decodeURIComponent(file.id).indexOf(',')>-1
        cmisId=file.id
      else
        cmisId=file.id+','+file.versionLabel
      postData={
        "cmisFileName":file.name
      }
      url =  CmisService.cpdfBaseUrl+'cpdfapi/v2/documents/drm/'+ encodeURIComponent(cmisId)+ '/updateFileName?access-token='+CmisService.token
      $.ajax({
        type: 'PUT'
        url: url,
        data: postData
        success: (data)->
          console.log(data)
          if data && data.code==100000
            if successfulCallback
              successfulCallback(data)
          else
            errCallback && errCallback(data)
        error: (err)->
          console.log(err)
          if err && err.code
            errCallback && errCallback(err)
      })
    deleteUserPermInCDrm: (drmMsgId,cDocId,successfulCallback,errCallback)->
      url = CmisService.cpdfBaseUrl+'cpdfapi/v2/documents/drm/revokePermission?drmPermissionID='+drmMsgId+'&cDocID='+encodeURIComponent(cDocId)+'&access-token='+CmisService.token
      $.ajax({
        type: 'DELETE'
        url: url
        success: (data)->
          console.log(data)
          if data && data.ret==0
            if successfulCallback
              successfulCallback(data)
          else
            errCallback && errCallback(data)
        error: (err)->
          console.log(err)
          errCallback && errCallback(err)
      })
    deleteAllUserPermInCDrm: (cDocId,successfulCallback,errCallback)->
      url = CmisService.cpdfBaseUrl+'cpdfapi/v2/documents/drm/revokeAllPermission?cDocID='+encodeURIComponent(cDocId)+'&access-token='+CmisService.token
      $.ajax({
        type: 'DELETE'
        url: url
        success: (data)->
          console.log(data)
          if data && data.ret==0
            if successfulCallback
              successfulCallback(data)
          else
            errCallback && errCallback(data)
        error: (err)->
          console.log(err)
          errCallback && errCallback(err)
      })
    requestForShare: (file,successfulCallback,errCallback)->
      url = CmisService.cpdfBaseUrl+'cpdfapi/v2/documents/drm/applyPermission?access-token='+CmisService.token
      cmisId=file.id
      if decodeURIComponent(file.id).indexOf(',')>-1
        cmisId=file.id
      else
        cmisId=file.id+','+file.versionLabel
      lang=localStorageService.get 'language' # CN
      fullLang=Utils.getFullLang(lang)  # zh-CN
      postData={
        "cmisObjectID":cmisId,
        "permission": [0],
        "reason": "",
        "notice": "1",
        "offlineDays": 0,
        "onlineDate": ""
        "lang":fullLang
      }
      $.ajax({
        type: 'POST'
        url: url
        data: postData
        success: (data)->
          console.log(data)
          if data && data.ret==0
            if successfulCallback
              successfulCallback(data)
          else
            errCallback && errCallback(data)
        error: (err)->
          console.log(err)
          errCallback && errCallback(err)
      })
    getCasTicket: (service,successfulCallback,errCallback)->
      url = CmisService.cpdfBaseUrl+'cpdfapi/v1/users/get-cas-ticket?userEmail=' + CmisService.email + '&access-token='+CmisService.token+'&service='+service;
      $.ajax({
        type: 'GET'
        url: url
        success: (data)->
          console.log(data)
          if data && data.ret==0
            if successfulCallback
              successfulCallback(data)
          else
            errCallback && errCallback(data)
        error: (err)->
          console.log(err)
          if err && err.code
            errCallback && errCallback(err)
      })
    addProtectTemplate: (postData,successfulCallback,errCallback)->
      url = CmisService.cpdfDocBaseUrl+'api/doc/tpl?access-token='+CmisService.token
      $.ajax({
        type: 'POST'
        url: url,
        data: postData
        success: (data)->
          console.log(data)
          if data && data.code==100000
            if successfulCallback
              successfulCallback(data)
          else
            errCallback && errCallback(data)
        error: (err)->
          console.log(err)
          if err && err.code
            errCallback && errCallback(err)
      })
    updateProtectTemplate: (postData,successfulCallback,errCallback)->
      url = CmisService.cpdfDocBaseUrl+'api/doc/tpl?access-token='+CmisService.token
      $.ajax({
        type: 'PUT'
        url: url,
        data: postData
        success: (data)->
          console.log(data)
          if data && data.code==100000
            if successfulCallback
              successfulCallback(data)
          else
            errCallback && errCallback(data)
        error: (err)->
          console.log(err)
          if err && err.code
            errCallback && errCallback(err)
      })
    getProtectTemplate: (successfulCallback,errCallback)->
      deffer=$q.defer()
      url = CmisService.cpdfDocBaseUrl+'api/doc/tpl?access-token='+CmisService.token
      $.ajax({
        type: 'GET'
        url: url,
        success: (data)->
          console.log(data)
          if data && data.code==100000
            if successfulCallback
              successfulCallback(data)
            deffer.resolve(data)
          else
            errCallback && errCallback(data)
            deffer.reject(data)
        error: (err)->
          console.log(err)
          if err && err.code
            errCallback && errCallback(err)
          deffer.reject(err)
      })
      deffer.promise
    setCdrmPermission: (postData,successfulCallback,errCallback)->
      url =  CmisService.cpdfBaseUrl+'cpdfapi/v2/documents/drm/setPermission?access-token='+CmisService.token
      lang=localStorageService.get 'language' # CN
      fullLang=Utils.getFullLang(lang)  # zh-CN
      postData.lang=fullLang
      $.ajax({
        type: 'POST'
        url: url,
        data: postData
        success: (data)->
          console.log(data)
          if data && data.ret==0
            if successfulCallback
              successfulCallback(data)
          else
            errCallback && errCallback(data)
        error: (err)->
          console.log(err)
          if err && err.code
            errCallback && errCallback(err)
      })

    getCDocInfoByCmisId: (cmisId,successfulCallback,errCallback)->
      defer=$q.defer()
      url =  CmisService.cpdfBaseUrl+'cpdfapi/v2/documents/drm/'+ encodeURIComponent(cmisId)+ '/acl?access-token='+CmisService.token
      $.ajax({
        type: 'GET'
        url: url,
        success: (data)->
          console.log(data)
          if data && data.ret==0
            if successfulCallback
              successfulCallback(data)
            defer.resolve(data)
          else
            errCallback && errCallback(data)
            defer.reject(data)
        error: (err)->
          console.log(err)
          if err && err.code
            errCallback && errCallback(err)
          defer.reject(err)
      })
      defer.promise
    getCmisInfoById: (cmisId,successfulCallback,errCallback)->
      url = CmisService.baseUrl+'api/document/cmis-document?object_id='+cmisId+'&access-token='+CmisService.token
      $.ajax({
        type: 'GET'
        url: url,
        success: (data)->
          console.log(data)
          if data && data.ret==0
            if successfulCallback
#              successfulCallback(sharedFileInfo)
              if data.data && data.data.cmis_document
                successfulCallback(data.data.cmis_document)
              else
                console.log('----qqqq')
          else
            errCallback && errCallback(data)
        error: (err)->
          console.log(err)
          if err && err.code
            errCallback && errCallback(err)
      })
    checkCDRMConvertingStatus: (convertMissionId,successfulCallback,errCallback)->
      url =  CmisService.cpdfBaseUrl+'cpdfapi/v2/documents/queryTask?access-token='+CmisService.token+'&fid='+convertMissionId
      $.ajax({
        type: 'GET'
        url: url,
        success: (data)->
          console.log(data)
          if data && data.ret==0
            if successfulCallback
#              successfulCallback(sharedFileInfo)
              successfulCallback(data)
          else
            errCallback && errCallback(data)
        error: (err)->
          console.log(err)
          if err && err.code==500
            errCallback && errCallback(err)
      })

    uploadToCWS:(targetFolderPath, file,fileName, successfulCallback, errCallback, progressFunc)->
      url =  CmisService.cpdfBaseUrl+'cpdfapi/v2/documents/drm/convert2CDRM?access-token='+CmisService.token
#      postData={
#        "file_url":fileUrl
#        "name":fileName
#        "fake":"true"
#      }
      postData = new FormData()
      postData.append("name",fileName)
      postData.append("filePath",targetFolderPath)
      postData.append("file",file)
      postData.append("chunks", 1)
      postData.append("chunk", 0)
      #      postData = new FormData()
      #      postData.append("object_id", file.id)
      #      postData.append("share_info", JSON.stringify(shareInfo))
      $.ajax({
        type: 'POST'
        url: url,
        beforeSend: (request)->
          request.setRequestHeader("Authorization", 'Bearer ' + CmisService.token)
        data: postData
        contentType: false
        processData: false
        success: (data)->
          console.log(data)
          if data && data.ret==0 && data.data && data.data.ID
            if successfulCallback
#              successfulCallback(sharedFileInfo)
              successfulCallback(data.data.ID)
          else
            console.log(data)
            if data && data.code
              errCallback && errCallback(data)
            if data && data.message != 'TOKEN_ERROR'
              Utils.warning(data.message)
        error: (err)->
          console.log(err)
          if err && err.code
            errCallback && errCallback(err)
        xhr: ()->
          #get the native XmlHttpRequest object
          xhr = $.ajaxSettings.xhr()
          #set the onprogress event handler
          xhr.upload.addEventListener("progress" , (evt)->
            if (evt.lengthComputable && progressFunc)
              progressFunc(evt)
          , false)
          # set the onload event handler
          xhr.upload.onload = ()->
            console.log('DONE!')
          #return the customized object
          xhr
      })

    
    uploadUrlToCmis:(fileUrl,fileName,successfulCallback,errCallback)->
      url =  CmisService.baseUrl+'cpdfapi/tools/swagger/cpdfapi.php?version=v2#!/documents-drm/convert_to_cpdf?access-token='+CmisService.token
#      postData={
#        "file_url":fileUrl
#        "name":fileName
#        "fake":"true"
#      }
      postData = new FormData()
      postData.append("file_url",fileUrl)
      postData.append("name",fileName)
      postData.append("fake", true)
      postData.append("auto_rename", true)
      #      postData = new FormData()
      #      postData.append("object_id", file.id)
      #      postData.append("share_info", JSON.stringify(shareInfo))
      $.ajax({
        type: 'POST'
        url:url,
        beforeSend: (request)->
          request.setRequestHeader("Authorization", 'Bearer ' + CmisService.token)
        data: postData
        contentType:false
        processData: false
        success: (data)->
          if data
            if successfulCallback
#              successfulCallback(sharedFileInfo)
              successfulCallback(data)
          else
            console.log(data)
            if data && data.code
              errCallback && errCallback(data)
            if data && data.message != 'TOKEN_ERROR'
              Utils.warning(data.message)
        error: (err)->
          console.log(err)
          if err && err.code
            errCallback && errCallback(err)
      })

    setDownloadPerm:(shareCode,disableDownload,successfulCallback,errCallback)->
      if window.FX || window.PhantomOnline
        Utils.connectCmis()
      url =  CmisService.baseUrl+'api/share/download-settings?access-token='+CmisService.token
      postData={
        "share_code": shareCode
        "can_download":if disableDownload then false else true
      }
      $.ajax({
        type: 'POST'
        url:url,
        beforeSend: (request)->
          request.setRequestHeader("Authorization", 'Bearer ' + CmisService.token)
        data: postData
        success: (data)->
          if data.data && data.ret == 0
            if successfulCallback
#              successfulCallback(sharedFileInfo)
              successfulCallback(data)
          else
            console.log(data)
            if data && errCallback
              errCallback(data)
#            if data && (data.message != 'TOKEN_ERROR' || data.msg != 'TOKEN_ERROR')
#              Utils.warning(data.msg || data.message)
        error: (err)->
          if err && errCallback
            errCallback(err)

          console.log(err)
      })
    setSharedInfo:(file,shareInfo,message,disableDownload,successfulCallback,errCallback)->
      # shareInfo  [{'everyone': 'cmis:write'},{'131122@mailinator.com': 'cmis:write'}]
      if window.FX || window.PhantomOnline
        Utils.connectCmis()
      currentUserId = CmisService.email
      url =  CmisService.baseUrl+'api/share/share?access-token='+CmisService.token
      if(shareInfo.length==0)
        userInfo={}
        shareInfo=[]
        userInfo[currentUserId]="cmis:all"
        shareInfo.push(userInfo)
      if(!message)
        message=''
      postData={
        "object_id":file.id
        "share_info":JSON.stringify(shareInfo)
        "message":message
        "can_download":if disableDownload then false else true,
        "lang": localStorage.getItem('share_plugin_lang') || Utils.getFullLang(localStorageService.get('language'))
      }
      if file.cDocId
        postData['cPdfId']=file.cDocId

#      postData = new FormData()
#      postData.append("object_id", file.id)
#      postData.append("share_info", JSON.stringify(shareInfo))
      $.ajax({
        type: 'POST'
        url:url,
        beforeSend: (request)->
          request.setRequestHeader("Authorization", 'Bearer ' + CmisService.token)
        data: postData
        success: (data)->
          if data.data && data.ret == 0
            if successfulCallback
#              successfulCallback(sharedFileInfo)
              successfulCallback(data)
          else
            console.log(data)
            if data && errCallback
              errCallback(data)
            if data && (data.message != 'TOKEN_ERROR' || data.msg != 'TOKEN_ERROR')
              Utils.warning(data.msg || data.message)
        error: (err)->
          if err && errCallback
            errCallback(err)

          console.log(err)
      })
    appendSharedInfo:(file,shareInfo,message,collect_feedback,successfulCallback,errCallback)->
      # shareInfo  [{'everyone': 'cmis:write'},{'131122@mailinator.com': 'cmis:write'}]
      if window.FX || window.PhantomOnline
        Utils.connectCmis()
      currentUserId = CmisService.email
      url =  CmisService.baseUrl+'api/share/share?access-token='+CmisService.token
      if(shareInfo.length==0)
        userInfo={}
        shareInfo=[]
        userInfo[currentUserId]="cmis:all"
        shareInfo.push(userInfo)
      if(!message)
        message=''
      postData={
        "object_id":file.id
        "share_info":JSON.stringify(shareInfo)
        "message":message
        "type":"append"
        "collect_feedback":collect_feedback
        "lang": localStorage.getItem('share_plugin_lang') || Utils.getFullLang(localStorageService.get('language'))
      }
      if file.cDocId
        postData['cPdfId']=file.cDocId

      #      postData = new FormData()
      #      postData.append("object_id", file.id)
      #      postData.append("share_info", JSON.stringify(shareInfo))
      $.ajax({
        type: 'POST'
        url:url,
        beforeSend: (request)->
          request.setRequestHeader("Authorization", 'Bearer ' + CmisService.token)
        data: postData
        success: (data)->
          if data.data && data.ret == 0
            if successfulCallback
#              successfulCallback(sharedFileInfo)
              successfulCallback(data)
          else
            console.log(data)
            if data && errCallback
              errCallback(data)
            if data && (data.message != 'TOKEN_ERROR' || data.msg != 'TOKEN_ERROR')
              Utils.warning(data.msg || data.message)
        error: (err)->
          if err && errCallback
            errCallback(err)

          console.log(err)
      })
    getSharedInfo:(file,force,successfulCallback,errCallback)->
#      sharedLink "http://docker.mydo.cx/Xjo"  Xjo
#      shareCode =file.sharedLink.split('/').pop()
      url =  CmisService.baseUrl+'api/share/share?access-token='+CmisService.token

      currentUserId = CmisService.email
      if(window.PhantomOnline && !currentUserId)
        currentUserId = localStorage.getItem('currentEmail')
      userInfo={}
      tempUserInfo={}
      shareInfo=[]
      userInfo[currentUserId]="cmis:all"
#      userInfo['guest']="cmis:read"
      shareInfo.push(userInfo)
      #add other direct user
      # cmis change everyone smx:none in direct so ignore it
      for item,key in file.aces
        if item.isDirect == true && item.userId!=file.createdBy.id && item.permission!='smx:none' && item.userId!='everyone'
          tempUserInfo[item.userId] = item.permission
          shareInfo.push(tempUserInfo)
      console.log(shareInfo);
      postData={
        "object_id":file.id
        "share_info":JSON.stringify(shareInfo)
      }
      if file.cDocId
        postData['cPdfId']=file.cDocId
      console.log(postData)
#      postData = new FormData()
#      postData.append("object_id", file.id)
#      postData.append("share_info", shareInfo)
      $.ajax({
        type: 'POST'
        url:url,
        beforeSend: (request)->
          request.setRequestHeader("Authorization", 'Bearer ' + CmisService.token)
        data: postData
        success: (data)->
          console.log('data')
          console.log(data)
          if data.data && data.ret == 0
            if successfulCallback
#              successfulCallback(sharedFileInfo)
              successfulCallback(data.data)
          else
            console.log(data)
            if data && data.message != 'TOKEN_ERROR'
              Utils.warning(data.message)
        error: (err)->
          console.log(err)
      })

    getAclByFileId:(fileId,SuccessCallback,ErrorCallback)->
      CmisService.session.getACL(fileId, true).ok (data)->
        _this.aces = (new Ace ace for ace in data.aces when ace.principal.principalId != 'everyone' && ace.permissions[0] != "cmis:all")
        SuccessCallback && SuccessCallback()
      .notOk (error)->
        if Utils.handleCmis401Error(error)
          return
        ErrorCallback && ErrorCallback(error)
    stopShare:(cmisId,successfulCallback,errCallback)->
      if window.FX || window.PhantomOnline
        Utils.connectCmis()
      url = CmisService.baseUrl+'api/share/share?access-token='+CmisService.token + '&time=' +Date.now();
      postData = {
        'object_id':cmisId,
        'share_info':JSON.stringify([])
      }
      $.ajax({
        type: 'POST',
        url: url,
        beforeSend: (request)->
          return request.setRequestHeader("Authorization", 'Bearer ' + CmisService.token);
        ,
        data: postData,
        success: (data)->
          if (data)
            if (data.ret == 0 && successfulCallback)
              return successfulCallback(data);
          else
            if(data)
              if(errCallback)
                errCallback(data);
        error: (err)->
          if(err)
            if(errCallback )
              return errCallback(err);
          else
            if(errCallback)
              return errCallback();
      })
    getRecentViewedFile:(query,successfulCallback)->
#      https://cloud-docker.connectedpdf.com/api/document/recent-files?access-token=58aa5d7de4b0b7dd7200ad18%2Cww002%40mailinator.com
      url =  CmisService.baseUrl+'api/document/recent-files?access-token='+encodeURIComponent(CmisService.token)
#          url =  'https://cloud-vagrant.connectedpdf.com'+'/api/share/public'
#            postData = new FormData()
      #      postData.append("code", code)
      postData={
        days:query
      }
      $.ajax({
        type: 'POST'
        url:url,
        beforeSend: (request)->
          request.setRequestHeader("Authorization", 'Bearer ' + CmisService.token)
        data: postData
        success: (data)->
#          return arr of object ids
          if data && successfulCallback
              successfulCallback(data)
          else
            console.log(data)
        error: (err)->
          console.log(err)
      })
    cmisSQL:(params,successfulCallback)->
#      post https://cloud-docker.connectedpdf.com/cmis/browser/fxcld?succinct=true&token=58b38d0ee4b0e5b2508af0e8%2Cww002%40mailinator.com&cmisaction=query&statement=SELECT%20*%20from%20cmis%3Adocument%20WHERE%20IN_TREE(%27cc76b247-9834-4e4c-972a-668452bdb6c5%27)&searchAllVersions=false
      if !params
        return
#      deffer = $.Deferred()
      url = CmisService.baseUrl+'cmis/browser/fxcld?'
      $.ajax({
        type: 'POST'
        url:url,
        beforeSend: (request)->
          request.setRequestHeader("Authorization", 'Bearer ' + CmisService.token)
        data:params
        success: (data)->
          #  生成 数组并返回
          if !data
            console.log(data)
        error: (err)->
          console.log(err)
      })
  }

##
#
#   all $http response-success or response-error handle token error
#
##
.factory('myInterceptor', ($log,$injector)->
#  $log.debug('$log is here to show you that this is a regular factory with injection')
  myInterceptor = {
    response:(data)->
      if data && data.data && data.data.message == 'TOKEN_ERROR'
        Utils = $injector.get('Utils')
        Utils.handleTokenError(data.data)
      data
    responseError:(data)->
      if data && data.data && data.data.message == 'TOKEN_ERROR'
        Utils = $injector.get('Utils')
        Utils.handleTokenError(data.data)
      data
  }
  myInterceptor
)
.factory("SelectMode",()->
  {
    on: false
    multipleChooseFiles: []
    multipleChooseFilesId: []
    closeSelectMode: (callback) ->
      _this = this
      if _this.multipleChooseFiles.length
        ref = _this.multipleChooseFiles
        i = 0
        len = ref.length
        while i < len
          file = ref[i]
          file.isSelected = false
          i++
      _this.multipleChooseFiles = []
      _this.multipleChooseFilesId=[]
      if callback
        callback()
    add: (file) ->
      _this = this
      index = _this.multipleChooseFiles.indexOf(file)

      if index == -1
        _this.multipleChooseFiles.push(file)
        _this.multipleChooseFilesId.push(file.id)
    'delete': (file) ->
      _this = this
      index = _this.multipleChooseFiles.indexOf(file)
      index2 = _this.multipleChooseFilesId.indexOf(file.id)
      _this.multipleChooseFiles.splice index, 1
      _this.multipleChooseFilesId.splice index2, 1
  }
)